package br.usp.ime.amazon;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ECS.client.jax.Item;
import com.ECS.client.jax.Items;
import com.ECS.client.jax.ItemLookupResponse;
import com.ECS.client.jax.ItemSearchResponse;


public class Search extends HttpServlet {

	private static final long serialVersionUID = 1L;
	public static final String AccessKeyId = "AKIAIHI5I2MDY5OUEFKQ";
	public static final String SecretId = "4t4E2ubVlAd682rCSWDa9BwqO+q80HO++cw977Om";
	public static final String AssociateTag = "httppessoalut-20";

	private AmazonWS aws= new AmazonWS(AccessKeyId, SecretId, AssociateTag);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		cleanSession(req);
		resp.sendRedirect("index.jsp");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		cleanSession(req);
		//Inicializa o serviço
		aws.initAwsService();
		
		//Inicializa o resultado
		ResultSearch r = new ResultSearch();
		
		//Retira da requisição os termos e monta a  string de busca (powersearch string)
		String search = doStringSearch(req);
		
		List<String> isbnList = new ArrayList<String>();
		
		int totalPages=0 , page=0;	

		do {
			
			page++;
			ItemSearchResponse response = aws.doSearch("Books", search, page);
					
			if(response.getItems()!=null){
				Items items = response.getItems().get(0);
				if(items.getTotalResults()!=null){
					r.setTotal(items.getTotalResults().intValue());
					totalPages = items.getTotalPages().intValue();
				
					for(Item i: items.getItem() ){
						Book l = new Book();
						l.setTitle(i.getItemAttributes().getTitle());
						l.setManufacture(i.getItemAttributes().getManufacturer());
						l.setASIN(i.getASIN());
						l.setDetailPageURL(i.getDetailPageURL());
						l.setAuthors(i.getItemAttributes().getAuthor());
						r.getBooks().add(l);
						isbnList.add(i.getASIN());
					}
				
					//busca detalhes dos 10 livros da consulta
					ItemLookupResponse lookupResponse=aws.doIsbnLookup(isbnList);
					//inclui os detalhes encontrados na lista de livros
					populateBookInformation(r.getBooks(),lookupResponse);
					//limpa a lista de livros para a proxima iteracao
					isbnList.clear();
				}
			}
		} while (page < totalPages	&& page < 10);
		if(r.getTotal()>0){
			req.getSession().setAttribute("result", r);
		}
		req.getSession().setAttribute("query", search);
		resp.sendRedirect("results.jsp");
	}
	
	private void cleanSession(HttpServletRequest req) {
		req.getSession().removeAttribute("result");
		req.getSession().removeAttribute("query");
	}
	
	private void populateBookInformation(List<Book> books, ItemLookupResponse response) {
		if (!response.getItems().get(0).getItem().isEmpty()){
			  Items items = response.getItems().get(0);
			  for (Item i: items.getItem()){
				  int pos=searchASIN(books,i.getASIN());
				  books.get(pos).setEdition(i.getItemAttributes().getEdition());
				  if (i.getItemAttributes().getISBN()!=null){
					  books.get(pos).setIsbn(i.getItemAttributes().getISBN());
				  	}
				  else {
					  books.get(pos).setIsbn(i.getASIN());
				  }
				  books.get(pos).setPublication(i.getItemAttributes().getPublicationDate());
				  if (i.getLargeImage()!=null){
					  books.get(pos).setUrlLargeImage(i.getLargeImage().getURL());
				  }
					  
				  if (i.getMediumImage()!=null){
					  books.get(pos).setUrlMediumImage(i.getMediumImage().getURL());
				  }
			  
			  };//end for

		}//end if
	}

	private String doStringSearch(HttpServletRequest req){
		List<String> list = new ArrayList<String>();
		
		String keywords = req.getParameter("keywords");
		String[] authors = req.getParameterValues("authors");
		String title = req.getParameter("title");
		String isbn = req.getParameter("isbn");
		String publisher = req.getParameter("publisher");
		String subject = req.getParameter("subject");
		String language = req.getParameter("language");
		String pubdate = req.getParameter("pubdate");	

		if(keywords.trim().length()>0){
			list.add("keywords: "+keywords.trim());			
		}
		
		String temp = "";
		
		if(authors[0].trim().length()>0){
			temp = " author: "+authors[0].trim();
		}
		if(authors.length>1){
			temp = " (" + temp;
			for(int i=1; i < authors.length;i++){
				if(authors[i].trim().length()>0){
					temp += " OR author: "+authors[i].trim();;
				}
			}
			temp += ")";
		}
	
		if(title.trim().length()>0){
			list.add("title: "+title.trim());
		}
		if(isbn.trim().length()>0){
			list.add("isbn: "+isbn.trim());
		}
		if(publisher.trim().length()>0){
			list.add("publisher: "+publisher.trim());
		}
		if(subject.length()>0){
			list.add("subject: "+subject.trim());
		}
		if(!pubdate.equals("alldate")){
			if(req.getParameter("month").length()>0)
				list.add("pubdate: "+pubdate.trim()+" "+req.getParameter("month")+"-"+req.getParameter("year"));
			else
				list.add("pubdate: "+pubdate.trim()+req.getParameter("year"));
		}
		if(language.length()>0){
			list.add("language: "+language.trim());
		}
		
		if(list.isEmpty() && temp.isEmpty()){
			return null;
		}
		String search ="";
		if(!list.isEmpty()){
			search = list.get(0);
		
			for(int i=1; i<list.size();i++){
				search += " OR "+list.get(i);
			}
		}
		search +=temp;
		System.out.println(search);
		return search;
	}
	
	private int searchASIN(List<Book> lista, String ASIN){
		int i=0;
		while (i<lista.size() && !(ASIN.equals(lista.get(i).getASIN())))
		{
				i++;
		}
		return i;
		
	}
}